package cn.gxm.tools.migration.address;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DataSaver {
    private Connection conn;
    private PreparedStatement pstmt;

    private int count;

    private String tableName;
    private String idName = "id";
    private String address1Name = "address1";
    private String address2Name = "address2";

    public DataSaver(String tableName, String idName, String address1Name, String address2Name) {
        this.tableName = tableName;
        this.idName = idName;
        this.address1Name = address1Name;
        this.address2Name = address2Name;
    }

    public void setConn(Connection conn) throws SQLException {
        conn.setAutoCommit(false);
        this.conn = conn;
        String sql = "UPDATE " + tableName + " SET " + address1Name + "=?, " + address2Name + "=? WHERE " + idName + "=?";
        pstmt = conn.prepareStatement(sql);
    }

    public void save(long id, String address1, String address2) throws SQLException {
        count++;
        pstmt.setString(1, address1);
        pstmt.setString(2, address2);
        pstmt.setLong(3, id);
        pstmt.addBatch();

        if (count % 1000 == 0) {
            pstmt.executeBatch();
        }
    }

    public void finish() throws SQLException {
        if (count % 1000 != 0) {
            pstmt.executeBatch();
        }
        conn.commit();

        pstmt.close();
        conn.close();
    }
}
